package com.rrs.client.fragment

import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.core.content.res.ResourcesCompat
import androidx.core.graphics.Insets
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.DividerItemDecoration
import com.google.gson.reflect.TypeToken
import com.rrs.client.MList
import com.rrs.client.R
import com.rrs.client.Response
import com.rrs.client.Utils
import com.rrs.client.adapter.PolicyAdapter
import com.rrs.client.databinding.FragmentIndexBinding
import com.rrs.client.entity.IndexCarousel
import com.rrs.client.entity.Policy
import com.rrs.client.fromLocal
import com.xuexiang.xui.widget.banner.widget.banner.BannerItem
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient


class IndexFragment(val systemBars: Insets?) : Fragment() {

    private lateinit var binding: FragmentIndexBinding
    lateinit var utils: Utils
    val client = OkHttpClient()

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        utils = Utils(requireContext())
        binding = FragmentIndexBinding.inflate(inflater, container, false)

        setListDecoration()

        loadData()

        binding.refresh.setColorSchemeColors(resources.getColor(R.color.colorPrimary, null))
        binding.refresh.setOnRefreshListener {
            loadData()
            binding.refresh.isRefreshing = false
        }

        return binding.root
    }

    private fun setListDecoration(){
        val decoration =
            DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL)
        decoration.setDrawable(
            ResourcesCompat.getDrawable(resources, R.drawable.divider, null)!!
        )
        binding.policyList.addItemDecoration(decoration)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun loadData() {
        loadBanner()
        loadPolicyList()
    }


    @RequiresApi(Build.VERSION_CODES.O)
    @OptIn(DelicateCoroutinesApi::class)
    private fun loadBanner() {
        var res: Response<IndexCarousel>

        val bannerList = ArrayList<BannerItem>()
        GlobalScope.launch(utils.globalScopeErrorHandler) {
            withContext(Dispatchers.IO) {
                val type = object : TypeToken<MList<IndexCarousel>>() {}.type
                res = utils.getObjsFromCloud<IndexCarousel>(
                    client,
                    "${resources.getString(R.string.ServerUrl)}/getIndexCarouselList",
                    type,
                    "indexCarouselList",
                    true
                )
                res.list.forEach { carousel ->
                    val item = BannerItem()
                    item.imgUrl = carousel.imgData
                    item.title = "乡兴助农"
                    bannerList.add(item)
                }
            }
            withContext(Dispatchers.Main) {
                if (res.source == fromLocal) {
                    utils.sendMsg("未连接服务器，已为您加载首页缓存")
                }
                binding.banner.setSource(bannerList)
                    .startScroll()
            }
        }
    }

    @OptIn(DelicateCoroutinesApi::class)
    private fun loadPolicyList() {
        var res: Response<Policy>

        GlobalScope.launch(utils.globalScopeErrorHandler) {
            withContext(Dispatchers.IO) {
                val type = object : TypeToken<MList<Policy>>() {}.type
                res = utils.getObjsFromCloud<Policy>(
                    client,
                    "${resources.getString(R.string.ServerUrl)}/getPolicyList",
                    type,
                    "policyList",
                    true
                )
            }
            withContext(Dispatchers.Main) {
                res.list.forEach { carousel ->
                    Log.d("", carousel.id.toString())
                }
                binding.policyList.adapter = PolicyAdapter(requireContext(), res.list)
            }
        }
    }

}